package com.dries.security.validate.code.captcha.image;

import com.dries.security.validate.code.captcha.SysCaptcha;
import com.dries.security.validate.code.impl.AbstractValidateCodeProcessor;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;

/**
 * @Description: 生成图形验证码
 * @Author ZSY
 * @createTime 2020/9/7 10:22
 */
@Slf4j
@Component("imageCaptcha")
public class ImageCodeProcessor extends AbstractValidateCodeProcessor<SysCaptcha> {

    private final DefaultKaptcha captcha;
    public ImageCodeProcessor(DefaultKaptcha captcha) {
        this.captcha = captcha;
    }

    /**
     * 发送校验码，由子类实现
     *
     * @param request
     * @param sysCaptcha
     * @throws Exception
     */
    @Override
    protected void send(ServletWebRequest request, SysCaptcha sysCaptcha) throws Exception {
        if (request.getResponse() != null) {
            ImageIO.write(captcha.createImage(sysCaptcha.getCode()), "JPEG", request.getResponse().getOutputStream());
        }
    }
}
